package test;
/**
 * TODO 多线程练习
 *
 * @author david
 * @version 1.0
 * @date 2021/4/20 14:56
 */
public class MultiThreadDemo {
    /**
     * 需求现在有100张火车票，有两个窗口同时抢火车票，请使用多线程模拟抢票效果。
     * Created by yz on 2018/04/01.
     */
    public static void main(String[] args) {
        // t1 t2同时共享同一变量trainCount
        ThreadTrain threadTrain = new ThreadTrain();
        Thread t1 = new Thread(threadTrain, "窗口1");
        Thread t2 = new Thread(threadTrain, "窗口2");
        t1.start();
        t2.start();
    }
}

// 售票窗口
class ThreadTrain implements Runnable {
    // 总共有100张火车票
    private int trainCount = 100;

    public void run() {
        while (trainCount > 0) {
            try {
                // 休眠50秒
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 出售火车票
            sale();
        }
    }

    // 卖票方法
    public void sale() {
        System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - trainCount + 1) + "张票");
        trainCount--;
    }
}